import { Folder } from './Folder';
import { ResponseParser } from './Helpers/ResponseParser';
import { Buffer } from "buffer";

export interface MessageHeaders {
  uid: string;
  size?: number;
  date?: number;
  from?: string;
  to?: string;
  cc?: string;
  bcc?: string;
  subject?: string;
  contentType?: string;
}

export class Message {
  private folder: Folder;
  private headers: MessageHeaders;

  constructor(folder: Folder, uid: string) {
    this.folder = folder;
    this.headers = { uid };
  }

  private getClient() {
    return this.folder['store']['client'];
  }

  // 获取邮件结构
  public async getHeaders() {
    if (!this.headers) {
      await this.folder.updateHeaders([this]);
    }
    return this.headers;
  }

  public get uid() {
    return this.headers.uid;
  }

  public get contentType() {
    return this.headers.contentType;
  }

  // 获取正文内容
  public async fetchBody(): Promise<{ html?: string; text?: string }> {
    const client = this.folder['store'].getClient();
    const response = await client.sendCommand(
      `UID FETCH ${this.uid} (BODY[])`
    );
    if (!response.ok) {
      throw new Error('获取正文失败');
    }
    const raw = ResponseParser.parseFetchBody(response.payload);

    // 提取 BODY[] 内容
    const bodyMatch = raw.match(/BODY\[\][^\r\n]*\{(\d+)\}\r\n([\s\S]*?)\)\r\n/);
    let bodyRaw = '';
    if (bodyMatch) {
      bodyRaw = bodyMatch[2];
    } else {
      bodyRaw = raw;
    }

    // 尝试提取 text/html 或 text/plain 部分
    let html: string | undefined;
    let text: string | undefined;

    // 提取 text/html
    const htmlMatch = bodyRaw.match(/Content-Type:\s*text\/html[\s\S]*?\r\n\r\n([\s\S]*?)(?:\r\n--|$)/i);
    if (htmlMatch) {
      html = htmlMatch[1].trim();
      // 检查是否 base64 编码
      if (/Content-Transfer-Encoding:\s*base64/i.test(bodyRaw)) {
        try {
          html = Buffer.from(html, 'base64').toString('utf-8');
        } catch {}
      }
    }

    // 提取 text/plain
    const textMatch = bodyRaw.match(/Content-Type:\s*text\/plain[\s\S]*?\r\n\r\n([\s\S]*?)(?:\r\n--|$)/i);
    if (textMatch) {
      text = textMatch[1].trim();
      if (/Content-Transfer-Encoding:\s*base64/i.test(bodyRaw)) {
        try {
          text = Buffer.from(text, 'base64').toString('utf-8');
        } catch {}
      }
    }

    // 如果都没有匹配到，直接返回全部内容
    if (!html && !text) {
      text = bodyRaw;
    }

    return { html, text };
  }
}
